/*
 * HashTable.cpp
 *
 *  Created on: Apr 13, 2013
 *      Author: Anthony Varghese
 */

#include <cstddef>
#include "HashTableEntry.h"
#include "HashTable.h"

namespace lab9 {

HashTable::HashTable(const unsigned int n): size(n) {
	if (n < 0)
		return;
	entryTable = new HashTableEntry*[ size ];
	for (unsigned int i=0; i<size; i++)
		entryTable[i] = nullptr;
}

HashTable::~HashTable() {
	for (unsigned int i=0; i<size; i++)
		delete entryTable[i];
	delete[] entryTable;
}

int HashTable::hashf( const int key ){
    unsigned int hash = (key % size);

    unsigned int iterations = 0;
    while ( entryTable[hash] != nullptr && entryTable[hash]->getKey() != key) {
          hash = (hash+1) % size;
          /*
           * To make sure we are not stuck in an infinite loop,
           *  we track the number of iterations.
           */
          if (++iterations > size)
        	  throw "Too many iterations in hashing function!";
    }
    return hash;
}

double HashTable::get( const int key){
    unsigned int hash = hashf( key );

    if ( entryTable[hash] == nullptr )
          return -1;
    else
          return entryTable[hash]->getValue();
}

void HashTable::add( const int key, const double v ){
	unsigned int hash = hashf( key );

    if ( entryTable[hash] != nullptr ) // key is already in use: do not add a new value.
          return;
    else
          entryTable[hash] = new HashTableEntry( key, v );

}


} /* namespace lab9 */
